package com.castle.fortress.admin.cms.fragment;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.castle.fortress.admin.cms.dto.CmsArticleDto;
import com.castle.fortress.admin.cms.service.CmsArticleService;
import com.castle.fortress.admin.utils.SpringUtils;
import org.beetl.core.tag.GeneralVarTagBinding;

import java.util.HashMap;
import java.util.Map;

/**
 * cms 文章标签
 * @author castle
 */
public class CmsArticleTag extends GeneralVarTagBinding {

	@Override
	public void render() {
		CmsArticleService cmsArticleService = SpringUtils.getBean(CmsArticleService.class);
		Map<String,Object> art = new HashMap<>();
		CmsArticleDto dto = null;
		Long id = null;
		//指定文章id
		if(containHtmlAttribute("id")&&StrUtil.isNotEmpty(getAttributeValue("id").toString())){
			try {
				id = Long.parseLong(getAttributeValue("id").toString());
			} catch (NumberFormatException e) {
				this.binds(art);
				this.doBodyRender();
				return;
			}
			//未指定id则返回空
		}else{
			this.binds(art);
			this.doBodyRender();
			return;
		}
		dto = cmsArticleService.cmsTagInfo(id);
		if(dto==null){
			this.binds(art);
			this.doBodyRender();
			return;
		}
		if(dto.getColData()!=null){
			art.putAll(dto.getColData());
		}
		art.putAll(BeanUtil.beanToMap(dto));
		//标题长度限制
		if(containHtmlAttribute("titlelen")&&StrUtil.isNotEmpty(getAttributeValue("titlelen").toString())){
			try {
				Integer titlelen = Integer.valueOf(getAttributeValue("titlelen").toString());
				if(titlelen>0&& dto!=null && StrUtil.isNotEmpty(dto.getTitle())){
					Integer len = dto.getTitle().length()-1;
					dto.setTitle(dto.getTitle().substring(0,(titlelen>len?len:titlelen)));
				}
			} catch (NumberFormatException e) {
				e.printStackTrace();
			}
		}
		//内容摘要长度
		if(containHtmlAttribute("infolen")&&StrUtil.isNotEmpty(getAttributeValue("infolen").toString())){
			try {
				Integer infolen = Integer.valueOf(getAttributeValue("infolen").toString());
				if(infolen>0&& dto!=null && StrUtil.isNotEmpty(dto.getInfo())){
					Integer len = dto.getInfo().length()-1;
					dto.setInfo(dto.getInfo().substring(0,(infolen>len?len:infolen)));
				}
			} catch (NumberFormatException e) {
				e.printStackTrace();
			}
		}
		this.binds(art);
		this.doBodyRender();
	}
}
